import formidable, { errors as formidableErrors } from "formidable";
const Store = require("electron-store");
const store = new Store();
import { rawStructure } from "../server";
import { fileType } from "../html/util";
import { folderTree } from "../server";
import { appendIdAndMove } from "../server";

export const upload = async (req, res) => {
  const form = formidable({});
  form.uploadDir = store.get("projectPath") + "\\tmp\\";
  let fields;
  let files;
  try {
    const [fields, files] = await form.parse(req);
    let fileName = "";
    let dest = "";
    let duplicate = false;
    let newName = "";

    files.file.forEach((el: any, seq: number) => {
      if (el.originalFilename.indexOf("/") > -1)
        fileName = el.originalFilename.substring(
          el.originalFilename.lastIndexOf("/") + 1
        );
      else fileName = el.originalFilename;

      dest = store.get("projectPath");

      switch (fileType(fileName)) {
        case "js":
        case "download":
          // need to ignore letter uppercase and lowercase, change to regExp
          if (rawStructure.js.indexOf(fileName) > -1) {
            // need to reassure that the new name is not exist!
            newName = rawStructure.js.length + fileName;
            dest += "\\res\\js\\" + newName;
            duplicate = true;
            folderTree.find((val) => val.fileName === fileName).duplicate =
              true;
          } else {
            dest += "\\res\\js\\" + fileName;
            rawStructure.js.push(fileName);
          }
          break;
        case "css":
        case "less":
          if (rawStructure.css.indexOf(fileName) > -1) {
            newName = rawStructure.css.length + fileName;
            dest += "\\res\\css\\" + newName;
            duplicate = true;
            folderTree.find((val) => val.fileName === fileName).duplicate =
              true;
          } else {
            dest += "\\res\\css\\" + fileName;
            rawStructure.css.push(fileName);
          }
          break;
        case "html":
        case "htm":
          if (rawStructure.html.indexOf(fileName) > -1) {
            newName = rawStructure.html.length + fileName;
            dest += "\\" + newName;
            duplicate = true;
            folderTree.find((val) => val.fileName === fileName).duplicate =
              true;
          } else {
            dest += "\\" + fileName;
            rawStructure.html.push(fileName);
          }
          break;
        default:
          if (fileName.endsWith("psd") || fileName.endsWith("Thumbs.db")) {
            // remove useless files
            return;
          }

          if (rawStructure.img.indexOf(fileName) > -1) {
            newName = rawStructure.img.length + fileName;
            dest += "\\res\\img\\" + newName;
            duplicate = true;
            folderTree.find((val) => val.fileName === fileName).duplicate =
              true;
          } else {
            dest += "\\res\\img\\" + fileName;
            rawStructure.img.push(fileName);
          }
          break;
      }

      folderTree.push({
        id: seq,
        originalFilename: el.originalFilename,
        fileName,
        duplicate,
        dest,
      });

      duplicate = false;
      newName = "";

      appendIdAndMove(el.filepath, seq, dest);
    });
    // console.log(folderTree, "folderTree");
    store.set("folderTree", JSON.stringify(folderTree));
    // store.set("uploadFolderPath", fields.uploadFolderPath[0] + "");
  } catch (err) {
    // example to check for a very specific error
    console.error(err);
    res.writeHead(err.httpCode || 400, { "Content-Type": "text/plain" });
    res.end(String(err));
    return;
  }
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ fields, files }, null, 2));
  return;
};
